{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([-0.04479629,  0.02826866, -0.02001933,  0.03184373], dtype=float32)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gym\n",
    "# 定义环境\n",
    "class MyWrapper(gym.Wrapper):\n",
    "\n",
    "    def __init__(self):\n",
    "        env = gym.make('CartPole-v1')\n",
    "        super().__init__(env)\n",
    "        self.env = env\n",
    "\n",
    "    def reset(self):\n",
    "        state,_ = self.env.reset()\n",
    "        return state\n",
    "    \n",
    "    def step(self,action):\n",
    "        state,reward,done,_,info = self.env.step(action)\n",
    "        return state,reward,done,info\n",
    "    \n",
    "\n",
    "MyWrapper().reset()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<__main__.CustomCallback at 0x1e2bcc72b50>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from stable_baselines3.common.callbacks import BaseCallback\n",
    "\n",
    "\n",
    "#Callback语法\n",
    "class CustomCallback(BaseCallback):\n",
    "\n",
    "    def __init__(self, verbose=0):\n",
    "        super().__init__(verbose)\n",
    "\n",
    "        #可以访问的变量\n",
    "        #self.model\n",
    "        #self.training_env\n",
    "        #self.n_calls\n",
    "        #self.num_timesteps\n",
    "        #self.locals\n",
    "        #self.globals\n",
    "        #self.logger\n",
    "        #self.parent\n",
    "\n",
    "    def _on_training_start(self) -> None:\n",
    "        #第一个rollout开始前调用\n",
    "        pass\n",
    "\n",
    "    def _on_rollout_start(self) -> None:\n",
    "        #rollout开始前\n",
    "        pass\n",
    "\n",
    "    def _on_step(self) -> bool:\n",
    "        #env.step()之后调用,返回False后停止训练\n",
    "        return True\n",
    "\n",
    "    def _on_rollout_end(self) -> None:\n",
    "        #更新参数前调用\n",
    "        pass\n",
    "\n",
    "    def _on_training_end(self) -> None:\n",
    "        #训练结束前调用\n",
    "        pass\n",
    "\n",
    "\n",
    "CustomCallback()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n",
      "40\n",
      "60\n",
      "80\n",
      "100\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<stable_baselines3.ppo.ppo.PPO at 0x1e2cbac7820>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from stable_baselines3 import PPO\n",
    "\n",
    "\n",
    "#让训练只执行N步的callback\n",
    "class SimpleCallback(BaseCallback):\n",
    "\n",
    "    def __init__(self):\n",
    "        super().__init__(verbose=0)\n",
    "        self.call_count = 0\n",
    "\n",
    "    def _on_step(self):\n",
    "        self.call_count += 1\n",
    "\n",
    "        if self.call_count % 20 == 0:\n",
    "            print(self.call_count)\n",
    "\n",
    "        if self.call_count >= 100:\n",
    "            return False\n",
    "\n",
    "        return True\n",
    "\n",
    "\n",
    "\n",
    "model = PPO('MlpPolicy', MyWrapper(), verbose=0)\n",
    "\n",
    "model.learn(8000, callback=SimpleCallback())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\Anaconda install\\envs\\Gym\\lib\\site-packages\\stable_baselines3\\common\\evaluation.py:67: UserWarning: Evaluation environment is not wrapped with a ``Monitor`` wrapper. This may result in reporting modified episode lengths and rewards, if other wrappers happen to modify these. Consider wrapping environment first with ``Monitor`` wrapper.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(61.05, 13.599540433411713)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from stable_baselines3.common.env_util import make_vec_env\n",
    "from stable_baselines3 import A2C\n",
    "from stable_baselines3.common.evaluation import evaluate_policy\n",
    "import gym\n",
    "\n",
    "\n",
    "def test_callback(callback):\n",
    "\n",
    "    #创建Monitor封装的环境,这会在训练过程中写出日志文件到models文件夹\n",
    "    env = make_vec_env(MyWrapper, n_envs=1, monitor_dir='models')\n",
    "\n",
    "    #等价写法\n",
    "    # from stable_baselines3.common.monitor import Monitor\n",
    "    # from stable_baselines3.common.vec_env import DummyVecEnv\n",
    "    # env = Monitor(MyWrapper(), 'models')\n",
    "    # env = DummyVecEnv([lambda: env])\n",
    "\n",
    "    #训练\n",
    "    model = A2C('MlpPolicy', env, verbose=0).learn(total_timesteps=10,\n",
    "                                                   callback=callback)\n",
    "\n",
    "    #测试\n",
    "    return evaluate_policy(model, MyWrapper(), n_eval_episodes=20)\n",
    "\n",
    "\n",
    "#使用Monitor封装的环境训练一个模型,保存下日志\n",
    "#只是为了测试load_results, ts2xy这两个函数\n",
    "test_callback(None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(9.4, 0.9695359714832659)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from stable_baselines3.common.results_plotter import load_results, ts2xy\n",
    "from stable_baselines3.common.callbacks import BaseCallback\n",
    "#保存最优模型\n",
    "class SaveOnBestTrainingRewardCallback(BaseCallback):\n",
    "\n",
    "    def __init__(self):\n",
    "        super().__init__(verbose=0)\n",
    "\n",
    "        self.best = -float('inf')\n",
    "\n",
    "    def _on_step(self):\n",
    "        #self.n_calls是个从1开始的数\n",
    "        if self.n_calls % 1000 != 0:\n",
    "            return True\n",
    "\n",
    "        #读取日志\n",
    "        x, y = ts2xy(load_results('models'), 'timesteps')\n",
    "\n",
    "        #求最后100个reward的均值\n",
    "        mean_reward = sum(y[-100:]) / len(y[-100:])\n",
    "\n",
    "        print(self.num_timesteps, self.best, mean_reward)\n",
    "\n",
    "        #判断保存\n",
    "        if mean_reward > self.best:\n",
    "            self.best = mean_reward\n",
    "            print('save', x[-1])\n",
    "            self.model.save('models/best_model')\n",
    "\n",
    "        return True\n",
    "\n",
    "\n",
    "test_callback(SaveOnBestTrainingRewardCallback())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Gym",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
